<script setup>
import request from '@/utils/request.js'
import { ref,onMounted } from 'vue'
import {
  Plus
} from '@element-plus/icons-vue'
import { getRowIdentity } from 'element-plus/es/components/table/src/util';
onMounted(()=>{
  getAllDept()
})
let tableData = ref([])
const getAllDept = () => {
  request.get("/api/depts").then(res=>{
    tableData.value=res.data 
  })
}
let addDeptButton = ref(false)
let form=ref({
  name:''
})
let addOrEdit=ref('')
const addDeptButton1 = () => {
  addDeptButton.value=true
  addOrEdit.value='add'
}
let deptId=ref(null)
const handleEdit = (index,row) => {
  form.value.name=row.name
  addDeptButton.value=true
  addOrEdit.value='edit'
  deptId.value=row.id
}
const addDeptPrimary = () => {//点击确定,添加部门修改部门
  addOrEdit.value=='add'&&request.post("/api/depts",form.value).then(res=>{
    if(res.code==0){
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      getAllDept()
      addDeptButton.value=false
    }
  })
  addOrEdit.value=='edit'&&request.put("/api/depts",{name:form.value.name,id:deptId.value}).then(res=>{
    if(res.code==0){
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      getAllDept()
      addDeptButton.value=false
    }
  })
}
const dialogcancel = () => {//点击取消,重置表单
  form.value={
    name:''
  }
}
const handleDelete = (index,row) => {

  request.delete("/api/depts/"+row.id).then(res=>{
    if(res.code==0){
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      getAllDept()
    }
  })
}
</script>

<template>
   <div>
    <el-button type="primary" size="large" @click="addDeptButton1"><el-icon>
      <Plus />
    </el-icon>新增</el-button>
    <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="id" label="序号" width="180" />
    <el-table-column prop="name" label="部门名称" width="180" />
    <el-table-column prop="updateTime" label="最后操作时间" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="addDeptButton" :title="addOrEdit=='add'?'新增部门':'修改部门'" width="500" draggable @close="dialogcancel">
    <el-form :model="form">
      <el-form-item label="部门名称" label-width="140px">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>

    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDeptButton = false">取消</el-button>
        <el-button type="primary" @click="addDeptPrimary">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>
